//
//  DTImageScale.m
//  DTStandApp
//
//  Created by dt-macmini-ios2 on 15/1/28.
//  Copyright (c) 2015年 dt. All rights reserved.
//

#import "DTImageScale.h"

@implementation DTImageScale
+(UIImage *)imageWithImage:(UIImage *)image scaledForMaxWidth:(float)width
{
    
    float newHeight = image.size.height/image.size.width*width;
    
    CGSize size = CGSizeMake(width, newHeight);
    
    // Create a graphics image context
    UIGraphicsBeginImageContext(size);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,size.width,size.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

+ (UIImage *)imageWithMaxSide:(CGFloat)length sourceImage:(UIImage *)image{
    CGFloat scale = [[UIScreen mainScreen] scale];
    CGSize imgSize = CWSizeReduce(image.size, length);
    UIImage *img = nil;
    
    UIGraphicsBeginImageContextWithOptions(imgSize, YES, scale);  // 创建一个 bitmap context
    
    [image drawInRect:CGRectMake(0, 0, imgSize.width, imgSize.height)
            blendMode:kCGBlendModeNormal alpha:1.0];              // 将图片绘制到当前的 context 上
    
    img = UIGraphicsGetImageFromCurrentImageContext();            // 从当前 context 中获取刚绘制的图片
    UIGraphicsEndImageContext();
   
    return img;
}


static inline CGSize CWSizeReduce(CGSize size, CGFloat limit)   // 按比例减少尺寸
{
CGFloat max = MAX(size.width, size.height);
if (max < limit) {
    return size;
}

CGSize imgSize;
CGFloat ratio = size.height / size.width;

if (size.width > size.height) {
    imgSize = CGSizeMake(limit, limit*ratio);
} else {
    imgSize = CGSizeMake(limit/ratio, limit);
}

return imgSize;
}

@end
